<template>
  <div class="main">
    <APPcall
      v-model:call-show="callShow"
      :each_status="each_status"
      :customerData="customerData"
      @callPhone="changeSend"
      :callInfo="callInfo"
      :uuid="uuid"
      @next="handleCallNext"
    ></APPcall>
    <receive
      v-if="tab == '领取客户'"
      @dialPop="callShowMethod"
      @customerData="customerDetail"
      @closePop="closePopMethod"
      @dataList="getDataList"
    ></receive>
    <lock
      v-if="tab == '锁定客户'"
      @dialPop="
        () => {
          callShow = true;
        }
      "
      @customerData="customerDetail"
      @closePop="closePopMethod"
    ></lock>
    <follow
      v-if="tab == '跟进客户'"
      @dialPop="
        () => {
          callShow = true;
        }
      "
      @customerData="customerDetail"
      @closePop="closePopMethod"
    ></follow>
    <deal
      v-if="tab == '成交客户'"
      @dialPop="
        () => {
          callShow = true;
        }
      "
      @customerData="customerDetail"
      @closePop="closePopMethod"
    ></deal>
    <div class="cardTab">
      <el-radio-group v-model="tab" size="large">
        <el-radio-button
          v-for="(item, index) in tabList"
          :key="index"
          :label="item.label"
          :value="item.label"
          @change="change"
        />
      </el-radio-group>
    </div>
  </div>
</template>

<script setup>
import receive from "./components/receive/index.vue";
import follow from "./components/follow/index.vue";
import lock from "./components/lock/index.vue";
import deal from "./components/deal/index.vue";
import APPcall from "./components/APPcall/index.vue";
import { ref, reactive, computed, onMounted } from "vue";

import { useUserStoreHook } from "@/store/modules/user";
import { getUser } from "@/api/user";
import { addCallLog } from "@/api/customer";
const staffId = ref("");
const customerData = ref({});
const DataList = ref([]); // 当前page全部数据
function getDataList(val) {
  // console.log('getDataList',val)
  DataList.value = val;
}
const handleCallNext = () => {
  console.log("handleCallNext", customerData.value);
  const index = DataList.value.findIndex(
    item => item.id == customerData.value.id
  );
  let nextIndex = index + 1;
  const total = DataList.value.length;
  if (index != -1) {
    if (nextIndex >= total) {
      nextIndex = 0;
    }
    // 直接重置为初始状态 免得污染到新的数据
    callInfo.value = { status: 0 };
    customerData.value = DataList.value[nextIndex];
    console.log("customerData", customerData.value);
  }
};
function customerDetail(val) {
  // console.log('customerData2',val)
  customerData.value = val;
}
function callShowMethod(val) {
  callShow.value = val;
}
function closePopMethod(val) {
  callShow.value = val;
}
const tabList = ref([]);
const tab = ref();
const callShow = ref(false);

/** 页面元素权限 */
const auth_element = computed(() => {
  return useUserStoreHook()?.auth_element;
});

/** 筛选完-页面元素权限 */
// if (auth_element.value) {
//   // 查询 onpage 为 "/customerManagement/myclient/index" 的所有数据
//   const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerManagement/myclient/index");
//   // 转换为对象形式
//   const homeDataObj = Object.fromEntries(homeData);
//   if (homeDataObj.mc_tab) {
//     let childs = homeDataObj.mc_tab.childs || []
//     let filterTableList = []
//     for (let i = 0; i < childs.length; i++) {
//       let item = { label: "", value: childs[i] }
//       console.log('----',item)
//       if (childs[i] == 'mc_lq') item.label = "领取客户"
//       if (childs[i] == 'mc_gj') item.label = "跟进客户"
//       if (childs[i] == 'mc_sd') item.label = "锁定客户"
//       if (childs[i] == 'mc_cj') item.label = "成交客户"
//       filterTableList.push(item)
//     }
//     if (filterTableList.length) {
//       tabList.value = filterTableList;
//       tab.value = filterTableList[0].label;
//       console.log(tabList.value)
//     }
//   }
// }
if (auth_element.value) {
  const homeData = Object.entries(JSON.parse(auth_element.value)).filter(
    ([key, value]) => value.onpage === "/customerManagement/myclient/index"
  );
  const homeDataObj = Object.fromEntries(homeData);
  if (homeDataObj.mc_tab) {
    let childs = homeDataObj.mc_tab.childs || [];
    let filterTableList = [];

    // 定义你想要的顺序
    const order = ["mc_lq", "mc_gj", "mc_sd", "mc_cj"];

    // 按照自定义顺序处理
    order.forEach(code => {
      if (childs.includes(code)) {
        let item = { value: code };
        if (code == "mc_lq") item.label = "领取客户";
        if (code == "mc_gj") item.label = "跟进客户";
        if (code == "mc_sd") item.label = "锁定客户";
        if (code == "mc_cj") item.label = "成交客户";
        filterTableList.push(item);
      }
    });

    if (filterTableList.length) {
      tabList.value = filterTableList;
      tab.value = filterTableList[0].label;
    }
  }
}
function change() {
  callShow.value = false;
}

//-----------------------1.长连接控制-----------------------

//1.1相关物料
//1.1.1WebSocket 实例
let ws = null;
//1.1.2重连超时控制
let reconnectTimeout = null;

const each_status = ref(""); // 判断app和pc是否登录 'pc'app未登录 'pc、app' 都已登录
const callInfo = ref({ status: 0 }); // 通话信息
const uuid = ref(""); // 通话id
//1.2建立socket连接
const connectWebSocket = () => {
  //ws=new WebSocket("ws://114.117.212.166:2345");
  ws = new WebSocket("wss://crm.wxbqq.com/wsa");
  ws.onopen = () => {
    ws.send(
      JSON.stringify({ action: "connection_mark", data: sendData.value })
    );
    console.log("WebSocket 连接已建立");
  };
  ws.onmessage = event => {
    console.log("onmessage-----", event.data);
    try {
      let data = JSON.parse(event.data);
      // 心跳连接事件
      if (data.action == "connection_beat") {
        if (data.each_status == "pc") {
          each_status.value = data.each_status;
        } else {
          each_status.value = data.each_status;
        }
      }
      // 通话状态事件
      if (data.action == "call_status") {
        callInfo.value = data.data;
        uuid.value = data.data.info.uuid;
        if (data.data.info.status == 3) {
          addCallLog({
            customer_id: customerData.value.id,
            uuid: data.data.info.uuid,
            merchant_id: customerData.value.merchant_id,
            staff_id: staffId.value,
            phone: customerData.value.phone,
            record: "",
            callTime: data.data.info.duration,
            status: data.data.info.status
          }).then(res => {
            if (res.code == 10000) {
              console.log("添加通话记录成功");
            }
          });
        }
      }
    } catch (e) {
      console.log("error----=====", e);
    }
  };
  ws.onerror = error => {
    console.error("WebSocket 发生错误", error);
  };
  ws.onclose = event => {
    console.log("WebSocket 连接已关闭", event.code);
  };
};

//1.3处理 WebSocket 连接断开后的重连
const handleReconnect = () => {
  if (reconnectTimeout) {
    // 如果已经在重连，避免重复重连
    return;
  }
  reconnectTimeout = setTimeout(() => {
    console.log("正在尝试重新连接 WebSocket...");
    connectWebSocket();
    reconnectTimeout = null; // 重连后清除重连超时
  }, 5000); // 5 秒后重连
};

//1.4发送心跳包
const sendData = ref({
  platform: "pc",
  staffId: ""
});

const sendHeartbeat = () => {
  if (ws && ws.readyState == WebSocket.OPEN) {
    ws.send(
      JSON.stringify({ action: "connection_beat", data: sendData.value })
    );
    console.log("发送心跳", sendData.value);
  }
};
// 发送拨打电话需要的消息
const callData = ref({
  platform: "pc",
  staffId: "",
  id: "",
  phone: ""
});
function changeSend() {
  callData.value.staffId = staffId.value;
  callData.value.id = customerData.value.id;
  callData.value.phone = customerData.value.phone;
  ws.send(JSON.stringify({ action: "call_phone", data: callData.value }));
  console.log("发送消息", callData.value);
}

//1.5检查WebSocket连接状态
const checkConnectionStatus = () => {
  if (ws.readyState === WebSocket.OPEN) {
    console.log("WebSocket 连接正常");
  } else if (ws.readyState === WebSocket.CONNECTING) {
    console.log("WebSocket 正在连接...");
  } else if (ws.readyState === WebSocket.CLOSING) {
    console.log("WebSocket 连接正在关闭...");
  } else if (ws.readyState === WebSocket.CLOSED) {
    console.log("WebSocket 连接已关闭，准备重连");
    handleReconnect();
  }
};

onMounted(() => {
  getUser().then(res => {
    if (res.code == 1000) {
      staffId.value = res.data.id;
      sendData.value.staffId = res.data.id;
      connectWebSocket();
      setInterval(sendHeartbeat, 5000); //发送心跳
      setInterval(checkConnectionStatus, 5000); //检查WebSocket状态
    }
  });
});
</script>

<style scoped lang="scss">
.main-content {
  margin: 0 !important;
}
.cardTab {
  padding: 16px;
  background-color: #fff;
}
</style>
